package EurekaClientGo

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/robfig/cron/v3"
	"net/http"
)

type EurekaClient struct {
	*cron.Cron
	ServiceUrl string
	InstanceInfo
}

func (thiz *EurekaClient) Register() {
	thiz.Cron = cron.New(cron.WithSeconds())
	url := thiz.ServiceUrl + "apps/" + thiz.AppName
	resp, err := thiz.makeJsonPost(url, thiz.InstanceInfo)
	println(resp, err)
	spec := "*/30 * * * * ?"
	thiz.Cron.AddFunc(spec, func() {
		thiz.Renew()
	})
}
func (thiz *EurekaClient) Renew() {
	url := thiz.ServiceUrl + "apps/" + thiz.AppName + "/" + thiz.InstanceId + "?status=" + string(thiz.Status) + "&lastDirtyTimestamp=" + fmt.Sprint(thiz.LastDirtyTimestamp)
	b := new(bytes.Buffer)
	req, _ := http.NewRequest(http.MethodPut, url, b)
	http.DefaultClient.Do(req)
}
func (thiz *EurekaClient) makeJsonPost(url string, data interface{}) (resp *http.Response, err error) {
	b := new(bytes.Buffer)
	json.NewEncoder(b).Encode(data)
	return http.Post(url, "application/json; charset=utf-8", b)
}
